package com.clickpaas.governmentcloud.service.policymatchextservice.impl;

import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.*;
import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.common.ConstantSuggest;
import com.clickpaas.governmentcloud.common.EnumCompanyType;
import com.clickpaas.governmentcloud.common.ServerResponse;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.service.policymatchextservice.MatchExtService;
import com.clickpaas.governmentcloud.utils.policycondcalutils.PolicyCondCal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @company <上海爱湃斯科技有限公司>
 * @email <zhihui.peng@clickpaas.com>
 * @author huiye
 * @decription: 上海市科技小巨人企业认定政策匹配
 * @date 2020/12/16 10:30 上午
 */
@Slf4j
@Service
public class LittleTechGiantServiceImpl implements MatchExtService {

    @Resource
    private PolicyCondCal policyCondCal;

    @Override
    public ServerResponse<?> isMatchSuccess(PolicyEntity policy) {
        /**
         * 建议
         */
        StringBuffer suggest = new StringBuffer();
        /**
         * 返回信息
         */
        ServerResponse<?> serverResponse = ServerResponse.createError(ConstantExt._ERROR_MESSAGE);
        /**
         * 评分
         */
        Integer score = ConstantExt._ZERO;
        /**
         * 是否快速匹配：Y->true,N->false
         */
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        /**
         *  必要条件判断
         */
        HashMap hashMap = necessCondi(policy);
        /**
         * 必要条件对快速匹配数据做处理（精确匹配、快速匹配）
         */
        boolean ifNecess=Boolean.parseBoolean(hashMap.get(ConstantExt._NECESS).toString());
        if(!ifNecess && isQuickMatch){
            return serverResponse;
        }
        /**
         * 累加必要条件评分
         */
        score = score + Integer.parseInt(hashMap.get(ConstantExt._SCORE).toString());
        suggest.append(hashMap.get(ConstantExt._SUGGEST).toString());

        HashMap suggAndScore = getScore(policy);
        /**
         * 累加评分
         */
        score = score + Integer.parseInt(suggAndScore.get(ConstantExt._SCORE).toString());
        /**
         * 评分为0，快速匹配不展示数据
         */
        if(score <= 0 && isQuickMatch){
            return serverResponse;
        }
        /**
         * 添加建议
         */
        suggest.append(suggAndScore.get(ConstantExt._SUGGEST).toString());
        /*if (suggest.length() == 0 && score >= 90) {
            suggest.append("建议申报");
        }*/
        /**
         * 快速匹配不添加建议
         */
        if (isQuickMatch){
            suggest = new StringBuffer();
        }
        /**
         * 必要条件不满足得0分
         */
        if(!ifNecess){
            score = 0;
        }
        return insertPolicyData(policy,score,suggest,serverResponse);
    }

    @Override
    public HashMap getScore(PolicyEntity policy) {
        HashMap<String, Object> returnValue = new HashMap<>();
        StringBuffer suggest = new StringBuffer();
        /**
         * 分值
         */
        Integer scoreSum = ConstantExt._ZERO;

        /**
         * 公司类型
         */
        List list = typeOfCompany(policy);

        if(null != list){
            /**
             * 制造类，非软件服务类
             */
            if(list.contains(EnumCompanyType._MANUFACTURING.getCompanyTypeEng())
                    && !list.contains(EnumCompanyType._SOFTTECHNOSERV.getCompanyTypeEng())){
                /**
                 * 制造类≧20%,研发分值得20分
                 */
                if (ConstantExt._MANUFACTURE<=policyCondCal.RDPersonRate(policy)){
                    scoreSum += 20;
                }else {
                    suggest.append(ConstantSuggest._TECH_RD_PERSONNEL);
                }
                /**
                 * 上年度主营业务收入在1亿元至10亿元之间,得10分
                 * 前3年主营业务收入或净利润平均增长率>20%
                 */
                if (null != policy.getBusinessIncomeOfLastYear()
                        &&(policyCondCal.aveGrowthRateIncome(policy)>20
                        ||policyCondCal.aveGrowthRateNetProfit(policy)>20)){
                    if (policy.getBusinessIncomeOfLastYear()>=10000
                            &&policy.getBusinessIncomeOfLastYear()<=100000){
                        scoreSum += 10;
                    }else {
                        suggest.append(ConstantSuggest._TECH_BUS_STATUS_INCOME);
                    }
                }else {
                    suggest.append(ConstantSuggest._TECH_BUS_STATUS_AVERAGE_GROWTH);
                }
            }
            /**
             * 软件或科技服务类
             */
            if(list.contains(EnumCompanyType._SOFTTECHNOSERV.getCompanyTypeEng())) {
                /**
                 * 软件或科技服务类≧50%,得20分
                 */
                if (policyCondCal.RDPersonRate(policy) >= ConstantExt._SOFT_TECH_SERVER) {
                    scoreSum += 20;
                } else {
                    suggest.append(ConstantSuggest._TECH_RD_PERSONNEL);
                }
                /**
                 * 上年度主营业务收入在1亿元至10亿元之间,得10分
                 * 前3年主营业务收入或净利润平均增长率>20%
                 */
                if (null != policy.getBusinessIncomeOfLastYear()
                        && (policyCondCal.aveGrowthRateIncome(policy) > 20
                        || policyCondCal.aveGrowthRateNetProfit(policy) > 20)) {
                    if (policy.getBusinessIncomeOfLastYear() >= 6000
                            && policy.getBusinessIncomeOfLastYear() <= 100000) {
                        scoreSum += 10;
                    } else {
                        suggest.append(ConstantSuggest._TECH_BUS_STATUS_INCOME);
                    }
                } else {
                    suggest.append(ConstantSuggest._TECH_BUS_STATUS_AVERAGE_GROWTH);
                }
            }
        }

        /**
         * 研发费用占比≧5%,得20分
         */
        if(policyCondCal.RDPersonCostRate(policy)>=ConstantExt._RD_PERSON_COST_RATE){
            scoreSum += 20;
        }else {
            suggest.append(ConstantSuggest._TECH_RD_EXPENSES);
        }

        /**
         * 负债率≦70%,得10分
         */
        if(policyCondCal.debtRatio(policy)<=70){
            scoreSum += 10;
        }else {
            suggest.append(ConstantSuggest._TECH_DEBT_RATIO);
        }

        /**
         * 是否建立制定并完善《企业研发的组织管理制度》等研发管理制度体系（知识产权保护、人才引进培养、创新激励），得10分
         */
        if(null != policy.getFormulatedAndImproved()
                && policy.getFormulatedAndImproved().equals(ConstantExt._YES)){
            scoreSum += 10;
        }else {
            suggest.append(ConstantSuggest._TECH_RD_MANAGEMENT);
        }
        /**
         * 是否有良好的经营管理团队，有较强的风险控制机制和健全的规章制度，得10分
         */
        if(null != policy.getRulesAndRegulations()
                &&policy.getRulesAndRegulations().equals(ConstantExt._YES)){
            scoreSum += 10;
        }else {
            suggest.append(ConstantSuggest._TECH_OTHER_MANAGEMENT);
        }

        /**
         * 知识产权得分
         * I类≧1 &&  Ⅱ类>6 18
         * Ⅱ类≧6     16分
         * Ⅱ类≧4	12分
         * Ⅱ类≧3	8分
         * Ⅱ类≧2	4分
         * Ⅱ类<2	0分
         */
        if(policyCondCal.IntellPropertyFirst(policy)>0){
            scoreSum+=18;
        }else if(policyCondCal.IntellPropertySecond(policy)>=6){
            scoreSum+=16;
        }else if(policyCondCal.IntellPropertySecond(policy)>=4){
            scoreSum+=12;
        }else if(policyCondCal.IntellPropertySecond(policy)>=3){
            scoreSum+=8;
        }else if(policyCondCal.IntellPropertySecond(policy)>=2){
            scoreSum+=4;
        }else {
            suggest.append(ConstantSuggest._TECH_INTELLECTUAL);
        }
        returnValue.put(ConstantExt._SCORE,scoreSum);
        returnValue.put(ConstantExt._SUGGEST,suggest);
        return returnValue;
    }

    @Override
    public ServerResponse insertPolicyData(PolicyEntity policy,Integer score,StringBuffer suggest,ServerResponse serverResponse) {
        /**
         * 查询当前政策信息
         */
        TPoliciesDTO policyInfo = policyCondCal.getPolicyInfo(ConstantExt._RECO_SHANGHAI_TECH_LITTLE_GIANT);

        if (null == policyInfo) {
            log.info("政策：【{}】查询不到",ConstantExt._RECO_SHANGHAI_TECH_LITTLE_GIANT);
            return serverResponse;
        }
        policyCondCal.insertCommonPolicyData(policy, policyInfo, score, suggest);
        return ServerResponse.createSuccess(ConstantExt._SUCCESS_MESSAGE);
    }

    /**
     * 必要条件判断
     *
     * @param policy
     * @return
     */
    @Override
    public HashMap necessCondi(PolicyEntity policy) {
        HashMap<String, Object> map = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        map.put(ConstantExt._NECESS,true);
        StringBuffer suggStr = new StringBuffer();
        /**
         * 是否快速匹配：Y->true,N->false
         */
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        /**
         * 快速匹配标识,必要条件：缺失字段默认给满分，有值进行判断
         */
        if (isQuickMatch && null == policy.getDishonesty()){
            //
        }else {
            /**
             * 是否违法
             */
            if(!policyCondCal.isIllegal(policy)){
                map.put(ConstantExt._NECESS,false);
            }
        }
        map.put(ConstantExt._SCORE,score);
        map.put(ConstantExt._SUGGEST,suggStr);
        return map;
    }

    /**
     * 判断公司类型
     * @param policy
     * @return
     */
    public List typeOfCompany(PolicyEntity policy){
        ArrayList<String> typeComStr = new ArrayList<>();
        if(null == policy.getIndustrys()) {
            return null;
        }
        List<String> industrys = policy.getIndustrys();
        for (String indu : industrys){
            if(indu.equals(EnumCompanyType._MANUFACTURING.getCompanyTypeChina())){
                typeComStr.add(EnumCompanyType._MANUFACTURING.getCompanyTypeEng());
            }
            if(indu.equals(EnumCompanyType._SOFTTECHNOSERV.getCompanyTypeChina())){
               typeComStr.add(EnumCompanyType._SOFTTECHNOSERV.getCompanyTypeEng());
            }
        }
        return typeComStr;
    }
}
